package com.sq.partner.manager.controller;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayMenu;
import com.sq.partner.manager.mybatis.model.GatewayScanUnionCode;
import com.sq.partner.manager.mybatis.model.GatewayScanUnionMenu;
import com.sq.partner.manager.service.UnionScanManagerService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.QRcodeUtil;
import com.sq.partner.manager.util.SqlUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lhy
 */
@Controller
@RequestMapping("/unionScanMenuConfig")
public class UnionScanMenuConfigController {

    private static Logger logger = LogUtil.getLog(UnionScanMenuConfigController.class);

    @Resource
    private UnionScanManagerService unionScanManagerService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String toListPage(){
        return "/unionScanMenuConfig/list";
    }





    /**
     * 根据条件查询出分页的一级菜单信息，并返回前端
     * @param page
     * @param menuName 一级菜单名称
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryMenuListByPageNumber")
    @ResponseBody
    public Page<GatewayScanUnionMenu> queryMenuListByPageNumber(Page<GatewayScanUnionMenu> page, String menuName) throws Exception{
        //处理分页信息
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        paramMap.put("menuName",null == menuName ? "" : menuName);
        page.setMap(paramMap);
        page = unionScanManagerService.queryMenuListByPageNumber(page);
        int dataSize = unionScanManagerService.queryMenuListByConditions(page);
        if (dataSize % page.getSize() == 0){
            page.setMaxPage(dataSize / page.getSize());
        }else {
            page.setMaxPage(dataSize / page.getSize() + 1);
        }
        return page;
    }


    /**
     * @author
     * @param page
     * @param unionScanQRCodeName 聚合二维码名称
     * @return 根据条件查询出分页的聚合二维码信息，并返回前端
     */
    @RequestMapping(value = "/queryUnionQRCodeListByPageNumber")
    @ResponseBody
    public Page<GatewayScanUnionCode> queryUnionQRCodeListByPageNumber(Page<GatewayScanUnionCode> page , String unionScanQRCodeName) throws Exception{
        Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
        paramMap.put("unionCodeName", unionScanQRCodeName==null?"":unionScanQRCodeName);
        page.setMap(paramMap);
        page = unionScanManagerService.queryUnionQRCodeListByPageNumber(page);
        int dataSize = unionScanManagerService.queryUnionCodeCountByConditions(page);
        if(dataSize%page.getSize() == 0){
            page.setMaxPage(dataSize/page.getSize());
        }else {
            page.setMaxPage(dataSize/page.getSize() +1 );
        }
        return page ;
    }


    /**
     * 根据菜单id 跳转到编辑页面，显示菜单信息
     * @param model
     * @param menuId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    public String toEditMenuPage(HttpServletRequest request, ModelMap model , String menuId,Integer menuSort) throws Exception{
        if(menuId == null ){
            return "参数错误";
        }
        model.put("type", "edit");
        model.put("menuId", menuId);
        model.put("menuName", URLDecoder.decode(request.getParameter("menuName"), "utf-8"));
        model.put("menuDesc", URLDecoder.decode(request.getParameter("menuDesc"), "utf-8"));
        model.put("menuSort", menuSort);
        return "/unionScanMenuConfig/addOrEdit";
    }

    @RequestMapping(value = "/add")
    public String toAddUnionCodePage(ModelMap model){
        model.put("type", "add");
        return "/unionScanMenuConfig/addOrEdit";
    }

    @RequestMapping(value = "/downloadQRCode")
    public void downloadQRCode(String ruleAgentId, HttpServletResponse response) throws Exception {
		/*//先查这个二维码
		GatewayScanUnionCode code = unionScanManagerService;
		//查二维码关联的菜单ID
		Integer menuId = code.getMenuId().intValue();
		//将其加密，作为参数拼接到URL中
		String idStr = RuleEncryptUtil.base64Encode(RuleEncryptUtil.encrypt(menuId.toString()));
		String picName=code.getUnionCodeName();*/
        String classPath=this.getClass().getResource("").getPath();
        String url = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/images/logo.png").replace("/WEB-INF", "");
        QRcodeUtil.QRcodeToStream1(response, Config.getProp("JHEWM.URL")+ruleAgentId, "", "聚合二维码", 300, 300,url);
    }


    /**
     * @since：2022年7月22日
     * @description 查可配置的子二维码信息（分页）
     * @param page
     * @param ruleId
     * @param agentId
     * @param planNo
     * @param riskMainType
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryScanCode")
    @ResponseBody
    public Page<Map<String,Object>> queryScanCode(Page<Map<String,Object>> page,String ruleId,String agentId,String planNo,String riskMainType,String unionCodeId,String menuId) throws Exception{
        Map<String,Object> paramap = SqlUtil.buildPageMap(page);
        paramap.put("ruleId", ruleId);
        paramap.put("agentId", agentId);
        paramap.put("planNo", planNo);
        paramap.put("riskMainType", riskMainType);
        paramap.put("unionCodeId", unionCodeId);
        paramap.put("menuId", menuId);
        page.setMap(paramap);
        page = unionScanManagerService.queryUnionCodeCanBeConfigByPageNumber(page);
        int dataSize = unionScanManagerService.queryUnionCodeCanBeCinfigCountByConditions(page);
        if(dataSize%page.getSize() == 0){
            page.setMaxPage(dataSize/page.getSize());
        }else {
            page.setMaxPage(dataSize/page.getSize() +1 );
        }
        return page ;
    }


    /**
     * @since：2022年7月26日
     * @description:分页查询已配置的二维码信息
     * @param page
     * @param ruleId
     * @param agentId
     * @param planNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryConfigedScanCode")
    @ResponseBody
    public Page<Map<String,Object>> queryConfigedScanCode(Page<Map<String,Object>> page,String ruleId,String agentId,String planNo,String menuId) throws Exception{
        Map<String,Object> paramap = SqlUtil.buildPageMap(page);
        paramap.put("ruleId", ruleId);
        paramap.put("menuId", menuId);
        paramap.put("agentId", agentId);
        paramap.put("planNo", planNo);
        page.setMap(paramap);
        page = unionScanManagerService.queryConfigedUnionCodeByPage(page);
        int dataSize = unionScanManagerService.queryConfigedUnionCodeCountByPage(page);
        if(dataSize%page.getSize() == 0){
            page.setMaxPage(dataSize/page.getSize());
        }else {
            page.setMaxPage(dataSize/page.getSize() +1 );
        }
        page.setResult("success");
        return page;
    }

    /**
     * @since：2022年7月28日
     * @description:删除某个已配置的方案
     * @param codeId
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/deleteConfigedUnionCode")
    @ResponseBody
    public Result deleteConfigedUnionCode(String codeId,String menuId) throws Exception{

        unionScanManagerService.deleteConfigedUnionCode(codeId);

        unionScanManagerService.checkAfterDelete(menuId,"P");
        return Result.success("删除成功");
    }

    /**
     * @since：2022年7月29日
     * @description：将方案关联至菜单上
     * @param unionCodeId
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/saveChecked")
    @ResponseBody
    public Result saveCheckedCodes(String unionCodeId,String ids,String names,String menuId) throws Exception{
        if(ids == null){
            return Result.error("传入参数为空");
        }

        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("menuId",menuId);
        String queryMenuLevel = unionScanManagerService.queryMenuLevel(hashMap);
        if (StringUtils.isEmpty(queryMenuLevel)){
            return Result.error("该菜单未关联一级菜单，不可关联方案");
        }

        boolean flag = unionScanManagerService.checkBeforeAdd(menuId, "P");
        if (!flag){
            return Result.error("该菜单已关联子菜单，不可再关联方案");
        }

        //转数组
        String[] id = ids.split(",");
        String[] name = names.split(",");
        boolean rs = unionScanManagerService.insertUnionCodeRela(id, unionCodeId,name,menuId,queryMenuLevel);

        if(rs){
            return Result.success("关联成功");
        }else {
            return Result.error("关联过程中出现问题!");
        }
    }

    /**
     * @since：2022年8月1日
     * @description:	增加新的聚合二维码
     * @param menuName
     * @param menuDesc
     * @param menuSort
     * @return
     * @throws Exception
     */
    @RequestMapping(value="addNewMenu")
    @ResponseBody
    public Result addNewMenu(String menuName,String menuDesc,String menuSort) throws Exception{
        Map<String,String> param = new HashMap<String, String>();
        param.put("codeName", menuName);
        param.put("codeDesc", menuDesc);
        param.put("menuSort", menuSort);
        if(menuName == null || menuName.length() == 0){
            return Result.error("菜单名称不可为空");
        }
        int rsId = unionScanManagerService.addNewMenu(param);
        if(rsId != 0){
            return Result.success("",rsId);
        }else {
            return Result.error("新增过程中出现问题！");
        }

    }

    @RequestMapping(value="/deleteMenu")
    @ResponseBody
    public Result deleteMenu(String menuId) throws Exception{

        if(menuId == null ){
            return  Result.fail();
        }

        /*
        删除菜单前先判断该菜单的菜单级别
            null:直接删除
            判断是否关联了方案，如果有，不可删除
            1:判断是否关联了方案二级菜单，如果有，不可删除。没有则级联删除二维码
            2:删除
        */

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("menuId",menuId);
        String menuLevel = unionScanManagerService.queryMenuLevel(map);

        if (menuLevel == null){
            unionScanManagerService.deleteMenu(menuId);
            return Result.success("删除成功");
        }

        Integer planCount = unionScanManagerService.selectPlanCountByMenuId(menuId);
        if (planCount != 0){
            return Result.fail("请先删除该菜单下关联的方案");
        }
        if ("1".equals(menuLevel)){
            Integer menuCount = unionScanManagerService.selectSubMenuCountByMenuId(menuId);
            if (menuCount != 0){
                return Result.fail("请先删除该菜单下关联的二级菜单");
            }else {
                unionScanManagerService.deleteMenu(menuId);
                unionScanManagerService.deleteUnionCodeByMenuId(menuId);
                return Result.success("删除成功");
            }
        }else if ("2".equals(menuLevel)){
            unionScanManagerService.deleteMenu(menuId);
            return Result.success("删除成功");
        }

        return Result.fail();
    }



}
